package ui;

import com.nanosl.lib.date.JXDatePicker;
import ent.CollectionReceipt;
import ent.Customer;
import ent.Item;
import ent.PriceList;
import ent.SaleCash;
import ent.SaleInvoice;
import ent.SaleInvoiceHasItem;
import ent.SaleInvoiceHasItemPK;
import ent.Stock;
import java.awt.Color;
import java.awt.Component;
import java.awt.GraphicsEnvironment;
import java.awt.Rectangle;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.swing.JComboBox;
import javax.swing.table.DefaultTableModel;
import org.jdesktop.swingx.autocomplete.AutoCompleteDecorator;
import util.Combo;
import util.Data;
import util.Printer;

/**
 *
 * @author Thilina
 */
public class POS extends ctrl.POS {

    private static POS instance = new POS();

    public static void display() {
        instance.setVisible(true);
        instance.requestFocus();
    }

    public static POS getInstance() {
        return instance;
    }

    public POS() {
        super();
        onLoad();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {
        java.awt.GridBagConstraints gridBagConstraints;

        jPanel1 = new javax.swing.JPanel();
        datePicker = new JXDatePicker();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        invoiceNumberField = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        customerComboBox = new javax.swing.JComboBox();
        jLabel4 = new javax.swing.JLabel();
        itemComboBox = new javax.swing.JComboBox();
        jLabel5 = new javax.swing.JLabel();
        quantityField = new javax.swing.JTextField();
        jLabel6 = new javax.swing.JLabel();
        priceField = new javax.swing.JTextField();
        jScrollPane1 = new javax.swing.JScrollPane();
        table = new javax.swing.JTable();
        jLabel8 = new javax.swing.JLabel();
        processButton = new javax.swing.JButton();
        clearButton = new javax.swing.JButton();
        totalAmountField = new javax.swing.JTextField();
        totalDiscountField = new javax.swing.JTextField();
        jLabel9 = new javax.swing.JLabel();
        jLabel7 = new javax.swing.JLabel();
        discountField = new javax.swing.JTextField();
        quantityLabel = new javax.swing.JLabel();
        jLabel10 = new javax.swing.JLabel();
        paidAmountField = new javax.swing.JTextField();
        jLabel11 = new javax.swing.JLabel();
        remainingAmountField = new javax.swing.JTextField();
        addCustomerButton = new javax.swing.JButton();
        jLabel12 = new javax.swing.JLabel();
        receiptNumberField = new javax.swing.JTextField();
        printCheckBox = new javax.swing.JCheckBox();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        getContentPane().setLayout(new java.awt.GridBagLayout());

        jPanel1.setBorder(javax.swing.BorderFactory.createLineBorder(new java.awt.Color(0, 0, 0)));

        datePicker.setName("datePicker"); // NOI18N
        datePicker.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                datePickerKeyPressed(evt);
            }
        });

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel1.setText("Date:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel2.setText("Invoice Number:");

        invoiceNumberField.setEditable(false);
        invoiceNumberField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        invoiceNumberField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                invoiceNumberFieldActionPerformed(evt);
            }
        });

        jLabel3.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel3.setText("Customer:");

        customerComboBox.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        customerComboBox.setName("customerComboBox"); // NOI18N
        customerComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                customerComboBoxActionPerformed(evt);
            }
        });
        customerComboBox.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                customerComboBoxKeyPressed(evt);
            }
        });

        jLabel4.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel4.setText("Item:");

        itemComboBox.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        itemComboBox.setName("itemComboBox"); // NOI18N
        itemComboBox.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                itemComboBoxActionPerformed(evt);
            }
        });
        itemComboBox.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                itemComboBoxKeyPressed(evt);
            }
        });

        jLabel5.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel5.setText("Quantity:");

        quantityField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        quantityField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                quantityFieldActionPerformed(evt);
            }
        });

        jLabel6.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel6.setText("Price:");

        priceField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        priceField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                priceFieldActionPerformed(evt);
            }
        });

        table.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        table.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "#", "Code", "Description", "Price", "Quantity", "Net", "Discount", "D%", "Amount"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false, false, false, false, false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        table.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                tableKeyReleased(evt);
            }
        });
        jScrollPane1.setViewportView(table);
        table.getColumnModel().getColumn(0).setPreferredWidth(25);
        table.getColumnModel().getColumn(1).setPreferredWidth(50);
        table.getColumnModel().getColumn(2).setPreferredWidth(300);
        table.getColumnModel().getColumn(3).setPreferredWidth(100);
        table.getColumnModel().getColumn(4).setPreferredWidth(50);
        table.getColumnModel().getColumn(5).setPreferredWidth(100);
        table.getColumnModel().getColumn(6).setPreferredWidth(50);
        table.getColumnModel().getColumn(7).setPreferredWidth(25);
        table.getColumnModel().getColumn(8).setPreferredWidth(100);

        jLabel8.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel8.setText("Total Amount:");

        processButton.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        processButton.setText("Process");
        processButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                processButtonActionPerformed(evt);
            }
        });

        clearButton.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        clearButton.setText("Clear");
        clearButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                clearButtonActionPerformed(evt);
            }
        });

        totalAmountField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        totalAmountField.setEnabled(false);

        totalDiscountField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        totalDiscountField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                totalDiscountFieldActionPerformed(evt);
            }
        });
        totalDiscountField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                totalDiscountFieldKeyReleased(evt);
            }
        });

        jLabel9.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel9.setText("Total Discount:");

        jLabel7.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel7.setText("Discount (%):");

        discountField.setEditable(false);
        discountField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        discountField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                discountFieldActionPerformed(evt);
            }
        });

        quantityLabel.setFont(new java.awt.Font("Tahoma", 1, 14)); // NOI18N
        quantityLabel.setText("0.0");

        jLabel10.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel10.setText("Paid Amount:");

        paidAmountField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        paidAmountField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                paidAmountFieldActionPerformed(evt);
            }
        });
        paidAmountField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                paidAmountFieldKeyReleased(evt);
            }
        });

        jLabel11.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel11.setText("Remaining Amount:");

        remainingAmountField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        remainingAmountField.setEnabled(false);

        addCustomerButton.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        addCustomerButton.setText("Add");
        addCustomerButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                addCustomerButtonActionPerformed(evt);
            }
        });

        jLabel12.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        jLabel12.setText("Receipt: ");

        receiptNumberField.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        receiptNumberField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                receiptNumberFieldActionPerformed(evt);
            }
        });
        receiptNumberField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyReleased(java.awt.event.KeyEvent evt) {
                receiptNumberFieldKeyReleased(evt);
            }
        });

        printCheckBox.setFont(new java.awt.Font("Tahoma", 1, 16)); // NOI18N
        printCheckBox.setText("Print Bill");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addComponent(processButton)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                            .addComponent(clearButton)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jLabel9))
                                        .addGroup(jPanel1Layout.createSequentialGroup()
                                            .addComponent(printCheckBox)
                                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                                            .addComponent(jLabel12)))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addComponent(receiptNumberField)
                                        .addComponent(totalDiscountField, javax.swing.GroupLayout.DEFAULT_SIZE, 120, Short.MAX_VALUE))
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                        .addComponent(jLabel10)
                                        .addComponent(jLabel8)))
                                .addGroup(jPanel1Layout.createSequentialGroup()
                                    .addGap(0, 0, Short.MAX_VALUE)
                                    .addComponent(jLabel11)))
                            .addGap(10, 10, 10)
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                .addComponent(remainingAmountField, javax.swing.GroupLayout.DEFAULT_SIZE, 151, Short.MAX_VALUE)
                                .addComponent(paidAmountField)
                                .addComponent(totalAmountField)))
                        .addComponent(jScrollPane1)
                        .addGroup(jPanel1Layout.createSequentialGroup()
                            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel2)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(invoiceNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, 74, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                                    .addComponent(jLabel1)
                                    .addGap(18, 18, 18)
                                    .addComponent(datePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addGap(18, 18, 18)
                                    .addComponent(jLabel3)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(customerComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 349, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGroup(javax.swing.GroupLayout.Alignment.LEADING, jPanel1Layout.createSequentialGroup()
                                    .addComponent(jLabel4)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(itemComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 649, javax.swing.GroupLayout.PREFERRED_SIZE)
                                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                    .addComponent(quantityLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)))
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(addCustomerButton)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addComponent(jLabel5)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(quantityField, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel6)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(priceField, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel7)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(discountField, javax.swing.GroupLayout.PREFERRED_SIZE, 72, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(datePicker, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(invoiceNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1)
                        .addComponent(jLabel3)
                        .addComponent(customerComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(addCustomerButton)))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel4)
                    .addComponent(itemComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(quantityLabel))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel5)
                    .addComponent(quantityField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel6)
                    .addComponent(priceField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel7)
                    .addComponent(discountField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(16, 16, 16)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 295, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(totalAmountField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel8)
                            .addComponent(totalDiscountField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel9))
                        .addGap(4, 4, 4)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(paidAmountField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel10)
                            .addComponent(receiptNumberField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel12))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(remainingAmountField, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel11)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(processButton)
                            .addComponent(clearButton))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(printCheckBox)))
                .addContainerGap())
        );

        gridBagConstraints = new java.awt.GridBagConstraints();
        gridBagConstraints.gridx = 0;
        gridBagConstraints.gridy = 0;
        gridBagConstraints.anchor = java.awt.GridBagConstraints.NORTHWEST;
        gridBagConstraints.insets = new java.awt.Insets(11, 10, 11, 10);
        getContentPane().add(jPanel1, gridBagConstraints);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void datePickerKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_datePickerKeyPressed
        if (evt.getKeyCode() == 10) {
            customerComboBox.requestFocus();
        }
    }//GEN-LAST:event_datePickerKeyPressed

    private void invoiceNumberFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_invoiceNumberFieldActionPerformed
        if (!invoiceNumberField.getText().trim().equals("")) {
            datePicker.requestFocus();
        }
    }//GEN-LAST:event_invoiceNumberFieldActionPerformed

    private void customerComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_customerComboBoxActionPerformed
    }//GEN-LAST:event_customerComboBoxActionPerformed

    private void customerComboBoxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_customerComboBoxKeyPressed
        if (evt.getKeyCode() == 10) {
            itemComboBox.requestFocus();
        }
    }//GEN-LAST:event_customerComboBoxKeyPressed

    private void itemComboBoxActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_itemComboBoxActionPerformed
        Item item = (Item) itemComboBox.getSelectedItem();
        PriceList priceList = item.getPriceList();
        quantityLabel.setText(nf2d.format(item.getStock().getQuantity()));
        priceField.setText(nf2d.format(priceList.getSellingPack()));
    }//GEN-LAST:event_itemComboBoxActionPerformed

    private void itemComboBoxKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_itemComboBoxKeyPressed
        if (evt.getKeyCode() == 10) {
            quantityField.requestFocus();
        } else if (evt.getKeyCode() == 192) {
            totalDiscountField.requestFocus();
            totalDiscountField.setSelectionStart(0);
        }
    }//GEN-LAST:event_itemComboBoxKeyPressed

    private void quantityFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_quantityFieldActionPerformed
        priceField.setSelectionStart(0);
        priceField.requestFocus();
    }//GEN-LAST:event_quantityFieldActionPerformed

    private void priceFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_priceFieldActionPerformed
        addToTable();
        itemComboBox.requestFocus();
    }//GEN-LAST:event_priceFieldActionPerformed

    private void tableKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_tableKeyReleased
        if (evt.getKeyCode() == 127) {
            dtm.removeRow(table.getSelectedRow());

            calcTotal();
        }
    }//GEN-LAST:event_tableKeyReleased

    private void processButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_processButtonActionPerformed
        process();
    }//GEN-LAST:event_processButtonActionPerformed

    private void clearButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_clearButtonActionPerformed
        clear();
    }//GEN-LAST:event_clearButtonActionPerformed

    private void paidAmountFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_paidAmountFieldKeyReleased
        calcRemaining();
    }//GEN-LAST:event_paidAmountFieldKeyReleased

    private void addCustomerButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_addCustomerButtonActionPerformed
        CustomerView.display();
    }//GEN-LAST:event_addCustomerButtonActionPerformed

    private void receiptNumberFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_receiptNumberFieldActionPerformed
        paidAmountField.requestFocus();
    }//GEN-LAST:event_receiptNumberFieldActionPerformed

    private void receiptNumberFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_receiptNumberFieldKeyReleased
    }//GEN-LAST:event_receiptNumberFieldKeyReleased

    private void discountFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_discountFieldActionPerformed
        addToTable();
        itemComboBox.requestFocus();
    }//GEN-LAST:event_discountFieldActionPerformed

    private void totalDiscountFieldKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_totalDiscountFieldKeyReleased
        substractDiscount();
    }//GEN-LAST:event_totalDiscountFieldKeyReleased

    private void paidAmountFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_paidAmountFieldActionPerformed
        process();
    }//GEN-LAST:event_paidAmountFieldActionPerformed

    private void totalDiscountFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_totalDiscountFieldActionPerformed
        paidAmountField.requestFocus();
    }//GEN-LAST:event_totalDiscountFieldActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(POS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(POS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(POS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(POS.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                POS dialog = new POS();
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton addCustomerButton;
    private javax.swing.JButton clearButton;
    private javax.swing.JComboBox customerComboBox;
    private org.jdesktop.swingx.JXDatePicker datePicker;
    private javax.swing.JTextField discountField;
    private javax.swing.JTextField invoiceNumberField;
    private javax.swing.JComboBox itemComboBox;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel10;
    private javax.swing.JLabel jLabel11;
    private javax.swing.JLabel jLabel12;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel7;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JLabel jLabel9;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTextField paidAmountField;
    private javax.swing.JTextField priceField;
    private javax.swing.JCheckBox printCheckBox;
    private javax.swing.JButton processButton;
    private javax.swing.JTextField quantityField;
    private javax.swing.JLabel quantityLabel;
    private javax.swing.JTextField receiptNumberField;
    private javax.swing.JTextField remainingAmountField;
    private javax.swing.JTable table;
    private javax.swing.JTextField totalAmountField;
    private javax.swing.JTextField totalDiscountField;
    // End of variables declaration//GEN-END:variables
    DefaultTableModel dtm;

    private void onLoad() {
        initComponents();

        AutoCompleteDecorator.decorate(itemComboBox);
        setComboBoxKeyAdapters(itemComboBox);
        datePicker.setFormats(yyyy_MM_dd);
//        KeyAdapter();
        dtm = (DefaultTableModel) table.getModel();
        clear();
    }

    private void setComboBoxKeyAdapters(JComboBox supp) {
        String compName = supp.getName();
        Component component[] = supp.getComponents();
        for (int i = 0; i < component.length; i++) {
            if (compName.equals("itemComboBox")) {
                component[i].addKeyListener(itemComboBoxKeyAdapter);
            }
        }
    }
    KeyAdapter itemComboBoxKeyAdapter = new java.awt.event.KeyAdapter() {
        @Override
        public void keyPressed(KeyEvent evt) {
            itemComboBoxKeyPressed(evt);
        }
    };

    private void clear() {
        dtm.setRowCount(0);
        Combo.fillCustomers(customerComboBox);
        Combo.fillItems(itemComboBox);
        clearFields();
    }

    private void clearFields() {
        invoiceNumberField.setText(Data.getInvoiceNo());
        quantityField.setText("");
        priceField.setText("");
        quantityLabel.setText("");
        discountField.setText("");
        totalAmountField.setText("");
        totalDiscountField.setText("");
        paidAmountField.setText("");
        remainingAmountField.setText("");
        itemComboBox.requestFocus();
//        receiptNumberField.setText(Data.getReceiptNo());
    }
    double totalAmount = 0;

    private void calcTotal() {
        totalAmount = 0;
        double totalDiscount = 0;
        for (int i = 0; i < table.getRowCount(); i++) {
            totalAmount += Double.valueOf(table.getValueAt(i, 8).toString());
            totalDiscount += Double.valueOf(table.getValueAt(i, 6).toString());
        }
        totalAmountField.setText("" + totalAmount);
        totalDiscountField.setText("" + totalDiscount);
        String paidText = paidAmountField.getText();
        if (paidText.equals("")) {
            paidAmountField.setText("0");
            remainingAmountField.setText("" + totalAmount);
        }
        calcRemaining();
    }

    private void calcRemaining() {
        String totalAmountText = totalAmountField.getText().trim();
        totalAmountText = totalAmountText.equals("") ? "0" : totalAmountText;
        String paidAmountText = paidAmountField.getText().trim();
        paidAmountText = paidAmountText.equals("") ? "0" : paidAmountText;
        double totalAmount1 = 0, paidAmount = 0, remainingAmount = 0;
        try {
            totalAmount1 = Double.parseDouble(totalAmountText);
        } catch (Exception e) {
        }
        if (totalAmount1 == 0) {
            return;
        }
        try {
            paidAmount = Double.parseDouble(paidAmountText);
        } catch (Exception e) {
        }
        remainingAmount = totalAmount1 - paidAmount;
        remainingAmountField.setText(nf2d.format(remainingAmount));
    }

    private void addToTable() {
        double quantity = 0;
        double price = 0;
        double discount = 0;
        double net = 0;
        Item item = (Item) itemComboBox.getSelectedItem();
        item = m.find(Item.class, item.getCode());
        double availableQuantity = item.getStock().getQuantity();

        try {
            quantity = Double.valueOf(quantityField.getText());
            price = Double.valueOf(priceField.getText().trim());
            discount = Double.valueOf(discountField.getText().trim());
        } catch (Exception e) {
        }

        if (quantity == 0) {
            setStatusMessage("Quantity Required", Color.RED);
            return;
        }

        if (quantity > availableQuantity) {
            setStatusMessage("Quantity not applicable!", Color.RED);
            return;
        }

//        if (price == 0) {
//            setStatusMessage("Price Required", Color.RED);
//            showError("Price Required");
//            return;
//        }
        net = price * quantity;
        double discountAmount = net * discount / 100;
        double amount = net - discountAmount;
        int i = dtm.getRowCount();
        Object[] rowData = {++i,
            item.getCode(),
            item.getDescription(),
            nf2d.format(price),
            nf3d.format(quantity),
            nf2d.format(net),
            nf2d.format(discountAmount),
            nf2d.format(discount),
            nf2d.format(amount)};

        dtm.addRow(rowData);
        quantityField.setText("");
        priceField.setText("");
        quantityLabel.setText("");
        discountField.setText("");
        calcTotal();
    }

    @Override
    public void setVisible(boolean b) {
        super.setVisible(b);
        Rectangle rectangle = GraphicsEnvironment.getLocalGraphicsEnvironment().getMaximumWindowBounds();
        setBounds(0, 50, rectangle.width, rectangle.height - 50);
        Combo.fillCustomers(customerComboBox);
        Combo.fillItems(itemComboBox);
//        customerComboBox.requestFocus();
        itemComboBox.requestFocus();
    }

    private void process() {
        int rowCount = table.getRowCount();
        if (rowCount == 0) {
            return;
        }

        String invoiceNumber = Data.getInvoiceNo();
        String ReceiptNumber = Data.getReceiptNo();
        if (invoiceNumber.equals("")) {
            invoiceNumberField.requestFocus();
            return;
        }
        Date date = datePicker.getDate();
        if (date == null) {
            datePicker.requestFocus();
            return;
        }

        Customer customer = (Customer) customerComboBox.getSelectedItem();
        double amount = Double.valueOf(totalAmountField.getText());
        double credit = Double.valueOf(remainingAmountField.getText());
        double discount = Double.valueOf(totalDiscountField.getText());
        SaleInvoice saleInvoice = new SaleInvoice(invoiceNumber);
        saleInvoice.setCustomer(customer);
        saleInvoice.setAmount(amount);
        saleInvoice.setCredit(credit);
        saleInvoice.setDiscount(discount);
        saleInvoice.setInvTime(date);
        saleInvoice.setReceivedAmount(0.0);
        saleInvoice.setEmployee(util.Data.getOperator().getEmployee());
        List<Serializable> serializables = new ArrayList<Serializable>();
        for (int i = 0; i < rowCount; i++) {
            Item item = m.find(Item.class, table.getValueAt(i, 1).toString());
            double quantity = Double.valueOf(table.getValueAt(i, 4).toString());
            double rate = Double.valueOf(table.getValueAt(i, 3).toString());
            double itemDiscount = Double.valueOf(table.getValueAt(i, 6).toString());
            SaleInvoiceHasItemPK saleInvoiceHasItemPK = new SaleInvoiceHasItemPK(invoiceNumber, item.getCode());
            SaleInvoiceHasItem sihi = new SaleInvoiceHasItem(saleInvoiceHasItemPK);
            sihi.setSaleInvoice(saleInvoice);
            sihi.setQuantity(quantity);
            sihi.setDiscount(itemDiscount);
            if (item.getStock() == null) {
                return;
            }
            Stock stock = item.getStock();
            quantity = stock.getQuantity() - quantity;
            stock.setQuantity(quantity);
            sihi.setItem(item);
            sihi.setCost(item.getPriceList().getCostPack());
            sihi.setRate(rate);
            serializables.add(sihi);
            serializables.add(stock);
        }
        serializables.add(saleInvoice);
        String paidAmountText = paidAmountField.getText().trim();
        paidAmountText = paidAmountText.equals("") ? "0" : paidAmountText;
        double paidAmount = 0;
        try {
            paidAmount = Double.parseDouble(paidAmountText);
        } catch (Exception e) {
        }
        if (paidAmount > 0) {
            if (ReceiptNumber.equals("")) {
                showError("Recipt Number Required!");
                return;
            }
            CollectionReceipt collectionReceipt = new CollectionReceipt(ReceiptNumber);
            collectionReceipt.setCollectedTime(date);
            collectionReceipt.setSaleInvoice(saleInvoice);
            collectionReceipt.setCash(paidAmount);
            SaleCash saleCash = new SaleCash(ReceiptNumber);
            saleCash.setAmount(paidAmount);
            saleCash.setCollectionReceipt(collectionReceipt);
            collectionReceipt.setSaleCash(saleCash);
            saleInvoice.setReceivedAmount(paidAmount);
            serializables.add(saleCash);
            serializables.add(collectionReceipt);
        }

        if (m.update(serializables)) {
//            SaleInvoicePaymentView.getInstance().fill(saleInvoice);
//            SaleInvoicePaymentView.display();
            if (printCheckBox.isSelected()) {
                Map<String, Object> params = Data.getParams();
                params.put("invoice", invoiceNumber);
                Printer.printPosInvoice(params);
            }
            setStatusMessage("Update success");
            Data.setInvoiceNo(invoiceNumber);
            Data.setReceiptNo(ReceiptNumber);
            clear();
        } else {
            setStatusMessage("Update failed", Color.RED);
        }
    }

    private void substractDiscount() {
        String totalDiscountText = totalDiscountField.getText().trim();
        double totalDiscount = 0;
        try {
            totalDiscount = Double.parseDouble(totalDiscountText);
        } catch (NumberFormatException numberFormatException) {
            totalDiscount = 0;
        }
        totalAmountField.setText(nf2d.format(totalAmount - totalDiscount));
    }
}
